package com.bsoft.advance.core.serialization;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 目标类需要实现Serializable接口
 */
public class Hessian2Serialization implements Serialization {
    @Override
    public <T> byte[] serialize(T obj) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output output = null;
        try {
            output = new Hessian2Output(os);
            output.writeObject(obj);
            output.flush();
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        try {
            Hessian2Input input = new Hessian2Input(bis);
            return (T)input.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
